package com.qf.springmvc02.controller;

import com.github.pagehelper.PageInfo;
import com.qf.springmvc02.entity.User;
import com.qf.springmvc02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;
import java.util.List;

/**
 * @author zed
 * @date 2022/5/7 16:24
 */
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/page/{num}")
    public String getUserByPage(@PathVariable("num") Integer pageIndex, Model model) {
        if (pageIndex <= 1) {
            pageIndex = 1;
        }
        PageInfo<User> pageInfo = userService.selectAllUser(pageIndex, 10);
        model.addAttribute("pageInfo", pageInfo);
        return "welcome";
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        // 直接跳转到添加页面
        return "add";
    }

    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id,Model model){
        // 根据ID查询要修改的数据
        User user = userService.selectById(id);
        model.addAttribute("user",user);
        return "update";
    }

    @PostMapping("/add")
    public String addUser(User user){
        // 补全注册时间
        user.setRegistTime(new Date());
        userService.addUser(user);
        // 添加完成后重定向到用户列表页
        return "redirect:/page/1";
    }

    @PostMapping("/update")
    public String updateUser(User user){
        // 执行用户修改
        userService.update(user);
        return "redirect:/page/1";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id")Integer id){
        userService.deleteById(id);
        // 重定向的地址建议使用绝对路径跳转
        return "redirect:/page/1";
    }

    // 根据名字模糊搜索用户
    @PostMapping("/search")
    public String search(String name,Model model){
        List<User> users = userService.selectByNameFuzzy(name);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        model.addAttribute("pageInfo",pageInfo);
        return "welcome";
    }

}
